package com.shuoyue.ffmpegvideocut.controller;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.shuoyue.ffmpegvideocut.ffmpegutil.FfmpegCmdHls4M3u8EncUtil;
import com.shuoyue.ffmpegvideocut.ffmpegutil.MyThreadPool;
import com.shuoyue.ffmpegvideocut.ffmpegutil.PasswordUtil;
import com.shuoyue.ffmpegvideocut.controller.oss.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.web.bind.annotation.*;

import java.io.*;

@RestController
@Scope("prototype")
@RequestMapping("/ffmpeg")
public class FFmpegController {
    @Autowired
    MinioConfig minioConfig;
    MyThreadPool pool = new MyThreadPool(10);

    /**
     * @return
     */
    @PostMapping("/cutVideoInOss")
    public ResultEntity cutVideoInOss(@RequestParam("bucketName") String bucketName,
                                      @RequestParam("filePath") String filePath,
                                      @RequestParam("callUrl") String callUrl,
//                                      @RequestParam("keyUrl") String keyUrl,
                                      @RequestParam("fragmentTimeSeconds") Integer fragmentTimeSeconds,
                                      @RequestParam("id") Long id) {
//        callUrl = "http://localhost:8012" + callUrl;//callUrl.startsWith("http")
        try {
            FfmpegCmdHls4M3u8EncUtil ffmpegCmdHls4M3u8EncUtil = new FfmpegCmdHls4M3u8EncUtil();

            if (fragmentTimeSeconds == null || fragmentTimeSeconds == 0) {
                fragmentTimeSeconds = 120;//默认2分钟一片
            }
            //搜索本地文件
            File fileVideo = new File(minioConfig.getRootPath() + File.separator + bucketName + File.separator + filePath);
            System.out.println("文件路径:" + fileVideo.getAbsolutePath());
            if (!fileVideo.exists()) {
                return ResultEntity.error("没有找到文件" + fileVideo.getAbsolutePath());
            }
            String finalCallUrl = callUrl;
            Integer finalFragmentTimeSeconds = fragmentTimeSeconds;
            pool.submit(() -> {
                String dirName = "video_" + java.util.UUID.randomUUID();
                File cutDir = new File(fileVideo.getParent(), dirName);
                cutDir.mkdirs();
                System.out.println("切片文件夹:" + cutDir.getAbsolutePath());
                System.out.println("文件路径2:" + fileVideo.getAbsolutePath());

//                String keyUrl = cutDir.getAbsolutePath().replace(minioConfig.getRootPath(), minioConfig.getM3u8KeyUrlPath()) + "/enc.key";
//                System.out.println("加密文件访问地址:" + keyUrl);

                //执行切片
                boolean isuc = ffmpegCmdHls4M3u8EncUtil.excudCmd(cutDir.getAbsolutePath(), fileVideo.getAbsolutePath(), minioConfig, String.valueOf(finalFragmentTimeSeconds.intValue()), fileVideo.getName());
                if (isuc) {
                    File[] files = cutDir.listFiles();
                    for (File f : files) {
                        String fileName = f.getName();
                        String suffix = fileName.substring(fileName.indexOf("."));

                        String m3FilePath = filePath.replace(fileVideo.getName(), "") + dirName + File.separator + "video.m3u8";

                        if (".m3u8".equals(suffix)) {
                            Files filesInfo = OssUtil.getFiles(bucketName,
                                    m3FilePath,
                                    fileName,
                                    "2",
                                    m3FilePath,
                                    OssUtil.convertFileSize(f.length()),
                                    suffix,
                                    0L);

                            filesInfo.setId(id);
                            filesInfo.setState(3);
                            HttpRequest post = HttpUtil.createPost(finalCallUrl);
                            post.body(JSON.toJSONString(filesInfo)).execute();
                        }
                    }
                } else {
                    Files files = new Files();
                    files.setId(id);
                    files.setState(2);
                    HttpRequest post = HttpUtil.createPost(finalCallUrl);
                    post.body(JSON.toJSONString(files)).execute();
                }


            });
        } catch (Exception e) {
            e.printStackTrace();
            Files files = new Files();
            files.setId(id);
            files.setState(2);
            HttpRequest post = HttpUtil.createPost(callUrl);
            post.body(JSON.toJSONString(files)).execute();
        }
        return ResultEntity.success("开始切片");
    }


    private boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            //递归删除目录中的子目录下
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }


}
